package com.own.demo.blockchain.bitcoin;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author liwenfeng
 * @Description dongruan
 * @Date 2023/07/18/17:51
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {
        // 创建一个空的区块链
        List<Block3> blockchain = new ArrayList<>();
        // 生成创世区块
        Block3 block3 = new Block3(1, System.currentTimeMillis(), new ArrayList<Transaction>(), 1, "1", "1");
        // 把创世区块加入到区块链里
        blockchain.add(block3);
        System.out.println(JSON.toJSONString(blockchain));
        // 放送方钱包地址
        String sender = "sender_wallet";
        // 接收方钱包地址
        String recipient = "recipient_wallet";
        // 创建一个空的钱包集合
        ArrayList<Transaction> txs = new ArrayList<>();
        // 挖矿
        Block3.minBlock(blockchain, txs, sender);
        System.out.println(sender + "钱包的余额为：" + getWalletBalance(blockchain, sender));
        // 创建一个新的交易集合
        ArrayList<Transaction> txs1 = new ArrayList<>();
        // 已发生但未记账的的交易记录，发送方给接收者转账3个比特币
        Transaction tx1 = new Transaction(UUID.randomUUID().toString(), sender, recipient, 3);
        // 已发生但未记账的交易记录，发送者给接收者转账1个比特币
        Transaction tx2 = new Transaction(UUID.randomUUID().toString(), sender, recipient, 1);
        txs1.add(tx1);
        txs1.add(tx2);
        // 挖矿
        Block3.minBlock(blockchain,txs1,sender);
        System.out.println(sender+"钱包的余额为:" + getWalletBalance(blockchain, sender));
        System.out.println(recipient+"钱包的余额为:" + getWalletBalance(blockchain, recipient));
    }
    // 查询余额
    public static int getWalletBalance(List<Block3> blockchain,String adress){
        int balance = 0;
        for (Block3 block3 : blockchain) {
            List<Transaction> transactions = block3.getTransactions();
            for (Transaction transaction : transactions){
                if(adress.equals(transaction.getRecipient())){
                    balance += transaction.getAmount();
                }
                if(adress.equals(transaction.getSender())){
                    balance -= transaction.getAmount();
                }
            }
        }
        return balance;
    }

}
